package com.cheli.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cheli.oss.service.OssService;
import com.cheli.oss.utils.ConstantUtils;
import lombok.val;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Auther: cl
 * @Date: 2020/10/22 15:06
 * @Description:
 */
@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {
       String endpoint = ConstantUtils.END_POINT;
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantUtils.KEY_ID;
        String accessKeySecret = ConstantUtils.KEY_SECRET;
        String bucketName = ConstantUtils.BUCKET_NAME;

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

       String fileName = file.getOriginalFilename();

       final String uuid = UUID.randomUUID().toString();
        fileName = uuid + fileName;

       // 2019/11/11/1.jpg
       String dataPath = new DateTime().toString("yyyy/MM/dd");
        fileName = dataPath + "/" +fileName;

       //参数1：bucket参数
       //参数3：上传文件输入流
        ossClient.putObject(bucketName, fileName, inputStream);

       ossClient.shutdown();

       String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

        return url;
    }
}
